package com.cindata

import com.cindata.dictionary.ExecStatusDict
import com.cindata.dictionary.EvaluateDict
import com.cindata.dictionary.AssessStatusDict
import grails.converters.JSON
import org.springframework.security.access.annotation.Secured

import grails.gorm.transactions.Transactional

@Secured(['permitAll'])
@Transactional
class ApiController
{
    static allowedMethods = [save: "POST", update: "PUT", delete: "DELETE"]
    def apiService
    def evaluateService
    def estateBatchEvaluateService

    /**
     * 评估结果回调
     **/
    def evaluateCallBack()
    {
        //接收参数

        def params = request.JSON
        println "callBack params:" + params

        // def params = readReqJSONParams(request.getReader())

        def evaluateCode = params?.evaluateCode
        def unitPrice = params?.unitprice ? params?.unitprice : 0
        def totalPrice = params?.saleprice ? params?.saleprice : 0
        def evaluateDate = params?.evaluateDate ? Date.parse("yyyy-MM-dd HH:mm:ss", params?.evaluateDate?.toString()) : null
        def communityId = params?.communityId
        def failReason = params?.failReason

        def batchEstate = BatchEstate.findByEvaluateCode(evaluateCode)
        def estateImport = EstateImport.findByEvaluateCode(evaluateCode)
        def assess = Assess.findByEvaluateCode(evaluateCode)
        if (!estateImport && !batchEstate && !assess)
        {
            render([message: "被评估的押品不存在", code: '1'] as JSON)
            return
        }

        // 重估回调
        if (batchEstate) 
        {
            println "********** 重估回调：batchEstateId: ${batchEstate?.id} *************"
            def estate = batchEstate?.estate
            if (totalPrice == 0)
            {
                //评估失败
                batchEstate.evaluateStatue = ExecStatusDict.FAILURE()
                batchEstate.failReason = failReason
                batchEstate.save(flush: true)
            }
            else
            {
                //评估成功
                estate.modifiedDate = new Date()
                estate.unitPrice = unitPrice
                estate.totalPrice = totalPrice
                estate.latestEvaluatePrice = totalPrice
                estate.latestEvaluateDate = evaluateDate
                estate.save(flush: true)

                batchEstate.evaluateStatue = ExecStatusDict.SUCCESS()
                batchEstate.evaluateDate = evaluateDate
                if (batchEstate.validate()) 
                {
                    batchEstate.save(flush: true)    
                }
                else
                {
                    println batchEstate.errors
                }

                def valuationHistory = ValuationHistory.findByEvaluateCode(evaluateCode)
                if (valuationHistory) 
                {
                    valuationHistory.valuationDate = evaluateDate
                    valuationHistory.unitPrice = unitPrice
                    valuationHistory.totalPrice = totalPrice
                    valuationHistory.evaluateCode = evaluateCode
                    valuationHistory.sourceClass = "estate"
                    valuationHistory.sourceId = estate?.id
                    valuationHistory.name = estate.communityName
                    valuationHistory.account = estate.account
                    valuationHistory.evaluateStatus = ExecStatusDict.SUCCESS()
                    valuationHistory.evaluateType = EvaluateDict.ARTIFICIAL()
                    if (valuationHistory.validate()) 
                    {
                        valuationHistory.save(flush: true)
                    }
                    else
                    {
                        println valuationHistory.errors
                    }
                }
                else
                {
                    println "未找到历史评估记录！"
                }

                estateBatchEvaluateService.updateBatchEstateCount(batchEstate.batch)
            }
        }
        else if (estateImport)
        {
            println "********** 导入回调：estateImport: ${estateImport?.id} *************"
            if (totalPrice == 0)
            {
                //评估失败
                estateImport.communityId = communityId as Long
                // estateImport.communityName = params?.info?.name
                // estateImport.communityAddress = params?.info?.address
                estateImport.unitPrice = unitPrice
                estateImport.evaluateDate = evaluateDate
                estateImport.failReason = failReason
                estateImport.evaluateStatue = ExecStatusDict.FAILURE()
                estateImport.save(flush: true)
                estateImport.evaluteFailure()
            }
            else
            {
                //评估成功
                estateImport.communityId = communityId as Long
                // estateImport.communityName = params?.info?.name
                // estateImport.communityAddress = params?.info?.address
                // estateImport.buildingId = params?.buildingId as Long
                // estateImport.unitId = params?.unitId as Long
                // estateImport.houseId = params?.houseId as Long
                estateImport.evaluateCode = evaluateCode
                estateImport.evaluateStatue = ExecStatusDict.SUCCESS()
                estateImport.unitPrice = unitPrice
                estateImport.totalPrice = totalPrice
                estateImport.evaluateDate = evaluateDate
                estateImport.latestEvaluateDate = evaluateDate
                // estateImport.buildYear = params?.info?.buildYear
                // estateImport.totalBuildingNum = params?.info?.totalBuildingNum
                // estateImport.totalHouseNum = params?.info?.totalHouseNum
                //没有坐标先用小区坐标代替
                if (estateImport.communityId)
                {
                    //小区详情
                    def community = apiService.community(estateImport?.city?.zoneNumber, estateImport.communityId)
                    if (community.data)
                    {
                        estateImport.x = community?.data?.x as double
                        estateImport.y = community?.data?.y as double
                    }
                }
                estateImport.save(flush: true)
                estateImport.evaluteSuccess()
                evaluateService.updateBatchCount(estateImport.batch)
                evaluateService.updateBatchTime(estateImport.batch)
            }
        }
        else if (assess)
        {
            println "********** 单笔评估回调：assess: ${assess?.id} *************"

            assess.assessUnitPrice = unitPrice
            assess.assessTotalPrice = totalPrice
            assess.evaluateDate = evaluateDate
            if (totalPrice == 0)
            {
                assess.assessStatus = AssessStatusDict.FAILURE()
                assess.failReason = failReason
            }
            else
            {
                assess.assessStatus = AssessStatusDict.SUCCESS()
            }
            if (!assess?.communityId && communityId != "-1")
            {
                assess?.communityId = communityId?.toInteger()
            }
            assess.save(flush: true)
        }

        render([message: "成功", code: '0'] as JSON)
    }

    // 读取请求的JSON参数
    private def readReqJSONParams(BufferedReader reader)
    {
        String line = null
        StringBuffer json = new StringBuffer()
        while ((line = reader.readLine()) != null)
        {
            json.append(line)
        }
        reader.close()
        def params = JSON.parse(json.toString())
        println "callBack params:" + params
        return params
    }
}
